package com.fangcang.service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.fangcang.dao.FailLogEntity;
import com.fangcang.dao.LogEntity;
import com.fangcang.dao.LogMapper;
import com.fangcang.elasticsearch.EsQueryParam;
import com.fangcang.elasticsearch.QunarPushStatisticService;
import com.fangcang.utils.LocalDateUtils;

@Service
public class TraceLogService {

	@Autowired	
	private QunarPushStatisticService service;

	@Resource
	private LogMapper logMapper;
	
	/**
	 * 写入单条日志记录
	 * @param log
	 */
	public void insertLog(FailLogEntity log) {
		logMapper.insert(log);
	}
	
	/**
	 * 批量写入日志记录
	 * @param logList
	 */
	public void batchInsertLogs(List<FailLogEntity> logList) {
		logMapper.batchInsert(logList);
	}
	
	
	@Transactional
	public void queryMerchantFailCount() {
		Map<String, String> termsMap = new HashMap<String, String>();
		termsMap.put("merchantCode.keyword", "count");
		termsMap.put("failType.keyword", "subCount");
		
		EsQueryParam queryParam = new EsQueryParam("fc-tracelog-delivery-server-quartz");
		queryParam.setAppName("hotel-delivery-server-quartz");
		queryParam.setBizName("qunar_push_change_price");
		LocalDateTime now = LocalDateTime.now();
		queryParam.setFromTime(LocalDateUtils.getFromTime(now));
		queryParam.setEndTime(LocalDateUtils.getEndTime(now));
		queryParam.setRangeField("startTime");
		
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("bizName", queryParam.getBizName());
		
		try {
			List<FailLogEntity>list = service.getMerchantFailCount(queryParam, queryMap, termsMap);
			if(!CollectionUtils.isEmpty(list)) {
				logMapper.batchInsert(list);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	@Transactional
	public void queryMerchantCount() {
		EsQueryParam queryParam = new EsQueryParam("fc-tracelog-delivery-server-quartz");
		queryParam.setAppName("hotel-delivery-server-quartz");
		LocalDateTime now = LocalDateTime.now();
		queryParam.setFromTime(LocalDateUtils.getFromTime(now));
		queryParam.setEndTime(LocalDateUtils.getEndTime(now));
		queryParam.setRangeField("startTime");
		try {
			List<LogEntity>list = service.getMerchantCount(queryParam );
			if(null != list && !list.isEmpty()) {
				logMapper.batchInsertLog(list);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
